package com.m.job.logs.service.impl;


import com.client.job.core.model.MJobRunLog;
import com.client.job.core.model.MJobRunLogsVo;
import com.m.job.logs.mapper.MJobRunLogsMapper;
import com.m.job.logs.model.MJobRunLogs;
import com.m.job.logs.model.dto.MJobRunLogsDto;
import com.m.job.logs.service.MJobRunLogsService;
import com.m.job.server.mapper.MJobInstanceMapper;
import com.m.job.server.model.MJobInstanceDto;
import com.m.utils.IdUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 */
@Service
public class MJobRunLogsServiceImpl implements MJobRunLogsService {

    @Resource
    private MJobRunLogsMapper mJobRunLogsMapper;

    @Resource
    private MJobInstanceMapper mJobInstanceMapper;

    @Override
    public int deleteByPrimaryKey(String runLogId) {
        return mJobRunLogsMapper.deleteByPrimaryKey(runLogId);
    }

    @Override
    public int insertSelective(MJobRunLogs record) {
        return mJobRunLogsMapper.insertSelective(record);
    }

    @Override
    public int insertMjobRunLog(MJobRunLogsVo logsVo) {
        //根据JobId和JobName查询，实例ID
        MJobInstanceDto instanceDto = new MJobInstanceDto();
        instanceDto.setAppName(logsVo.getAppName());
        instanceDto.setPort(logsVo.getPort());
        instanceDto.setJobId(logsVo.getJobId());
        instanceDto.setJobName(logsVo.getJobName());
        List<MJobInstanceDto>  instanceList = mJobInstanceMapper.getExctList(instanceDto);
        if(instanceDto == null || instanceList.isEmpty()){
            return 0;
        }
        String isntanceId = instanceList.get(0).getMachineId();
        //构建插入数据
        List<MJobRunLog> loglist = logsVo.getLogList();
        List<MJobRunLogs> runLogsList = new ArrayList<>();
        for (MJobRunLog temp : loglist) {
            runLogsList.add(MJobRunLogs.builder().runLogId(IdUtil.genId()).instanceId(isntanceId).dealTime(temp.getDealTime()).logMsg(temp.getLog()).build());
        }
        if(!runLogsList.isEmpty()){
            mJobRunLogsMapper.insertBatch(runLogsList);
        }
        return 0;
    }


    @Override
    public int updateByPrimaryKeySelective(MJobRunLogs record) {
        return mJobRunLogsMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public List<MJobRunLogsDto> list(MJobRunLogsDto mJobRunLogsDto) {
        return mJobRunLogsMapper.listLogs(mJobRunLogsDto);
    }


}
